﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;

namespace TeamsPortal.DataAccess
{
    public class ImageInfoDataAccess : BaseDataAccess
    {
        public ImageInfo Add(string path, int editorUserId)
        {
            DbCommand cmd = GetCommand("SPImagesInfoInsert");
            cmd.AddParameter<string>(Factory, "path", path);
            cmd.AddParameter<int>(Factory, "editorUserId", editorUserId);
            DbParameter idParameter = cmd.AddParameter(Factory, "imageId", DbType.Int32, null);
            idParameter.Direction = ParameterDirection.Output;

            cmd.SafeExecuteNonQuery();

            var result = new ImageInfo() { Path = path };

            if (idParameter.Value != DBNull.Value)
                result.Id = Convert.ToInt32(idParameter.Value);
            else
                throw new DataException("No value for the output parameter: " + idParameter.ParameterName);

            return result;
        }

        public ImageInfo Get(int id)
        {
            DbCommand cmd = GetCommand("SPImagesInfoGetById");
            cmd.AddParameter<int>(Factory, "id", id);

            DataRow row = GetFirstRow(cmd);

            ImageInfo result = null;
            if (row != null)
            {
                result = new ImageInfo();
                result.Id = row.Get<int>("Id");
                result.Path = row.Get<string>("Path");
            }

            return result;
        }

        public void Remove(int id)
        {
            DbCommand cmd = GetCommand("SPImagesInfoRemoveById");
            cmd.AddParameter<int>(Factory, "id", id);

            cmd.SafeExecuteNonQuery();
        }
    }
}
